﻿using QD.Tools;
using QD_Clients.Code;
using QD_Clients.Code.DbContent;
using QD_Clients.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity.Validation;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QD_Clients
{
    public partial class PMtableSettings : BaseForm
    {
        DataTable _dt;
        public PMtableSettings()
        {
            InitializeComponent();

            base.ToolsBtnUpdate = this.toolStripButton5;
            this.grid_list.InitGrid();
            this.grid_list.RowTemplate.ContextMenuStrip = this.contextMenuStrip1;

        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            GridList_DataBind();
        }

        private void txtKey_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                toolStripButton6_Click(sender, e);
            }
        }

        //string sqlConString = "server=47.106.217.227;uid=sa;pwd=QiDian2017;database=QDResources";
        //SqlConnection sqlConnect;
        //SqlCommand selectCommand;
        //SqlDataAdapter da = new SqlDataAdapter();
        //DataSet dataset = new DataSet();
        private void GridList_DataBind()
        {
            QDResources db = new QDResources();
            string key = this.txtKey.Text.Trim().ToLower();
            List<string> listWhere = new List<string>();
            string strWhere = " where 1=1 ";
            if (this.checkBox1.Checked)
            {
                listWhere.Add("TableType=0");
            }
            if (this.checkBox2.Checked)
            {
                listWhere.Add("TableType=1");
            }
            if (this.checkBox3.Checked)
            {
                listWhere.Add("TableType=2");
            }
            if (listWhere.Count > 0)
            {
                strWhere += " and (" + string.Join(" or ", listWhere) + ")";
            }

            if (!string.IsNullOrEmpty(key))
            {
                strWhere += string.Format(" and (SysTableName like '%{0}%' or SysTable like '%{0}%')", key);
            }

            string sql = "select SysTable,SysTableName,(case WHEN TableType=0 THEN '平台程序配置' WHEN TableType=1 THEN '平台报表配置' WHEN TableType=2 THEN '客户数据' END) TableType from Sys_ConfigTable";

            _dt = db.Query(sql + strWhere);
            this.grid_list.DataSource = _dt;

            this.grid_list.EndEditState();
            DataTable dt_form = _dt;
            if (dt_form != null && dt_form.Rows.Count > 0)
            {
                for (int i = 0; i < dt_form.Rows.Count; i++)
                {
                    if (dt_form.Rows[i]["TableType"].ToString() == "平台程序配置")
                    {
                        grid_list.Rows[i].Cells["ListTableType"].Style.BackColor = Color.Aquamarine;
                        ////定位到指定行（样式）
                        //grid_list.ClearSelection();
                        //grid_list.Rows[i].Selected = true;

                        ////让指定行处于选中状态（状态）
                        //grid_list.CurrentCell = grid_list.Rows[i].Cells[1];
                        //grid_list.CurrentRow.Selected = true;
                    }
                    else if (dt_form.Rows[i]["TableType"].ToString() == "平台报表配置")
                    {
                        grid_list.Rows[i].Cells["ListTableType"].Style.BackColor = Color.Coral;
                    }
                    else
                    {
                        grid_list.Rows[i].Cells["ListTableType"].Style.BackColor = Color.LightSeaGreen;
                    }
                }

            }



            //this.grid_list.RowLeave += grid_list_RowLeave;

            //        sqlConnect = new SqlConnection(sqlConString);
            //        selectCommand = new SqlCommand(sql);
            //        selectCommand.Connection = sqlConnect;
            //        da.SelectCommand = selectCommand;
            //        da.Fill(dataset, "Sys_ConfigTable");

            //        BindingSource bindingsource = new BindingSource();
            //        grid_list.DataSource = bindingsource;
            //        bindingsource.DataSource = dataset.Tables[0];
            //        grid_list.AutoResizeColumns(
            //        DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
            //        bindingsource.BindingComplete +=
            //new BindingCompleteEventHandler(bindingSource1_BindingComplete);
            //        grid_list.EndEdit();
            //        dataset.GetChanges();
            //        dataset.AcceptChanges();
            //        da.Update(dataset.Tables["Sys_ConfigTable"]);
        }

        private void 复制单元格ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.grid_list.CopyFirstSelectedCellValue();
        }

        private void 复制所有选中单元格ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.grid_list.CopySelectedCellsValue();
        }
        private void 删除选中项ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.grid_list.DeleteSelectedRows();
        }
        protected override void ToolsBtnUpdate_Click(object sender, EventArgs e)
        {
            DataTable dt_form = _dt;
            if (dt_form != null)
            {
                this.grid_list.EndEditState();
                DataTable tables = dt_form.GetChanges();
                if (tables != null && tables.Rows.Count > 0)
                {
                    tables = dt_form.GetChanges();
                    QDResources db = new QDResources();

                    for (int i = 0; i < tables.Rows.Count; i++)
                    {
                        switch (tables.Rows[i].RowState)
                        {
                            case DataRowState.Added:
                                {
                                    var id = tables.Rows[i]["SysTable"].ToString();
                                    if (!db.Sys_ConfigTable.Any(p => p.SysTable == id))
                                    {
                                        Sys_ConfigTable detail = new Sys_ConfigTable();
                                        detail.SysTableName = tables.Rows[i]["SysTableName"].ToString();
                                        detail.SysTable = id;
                                        var tableType = 0;
                                        if (tables.Rows[i]["TableType"].ToString() == "平台报表配置")
                                        {
                                            tableType = 1;
                                        }
                                        else if (tables.Rows[i]["TableType"].ToString() == "客户数据")
                                        {
                                            tableType = 2;
                                        }
                                        detail.TableType = tableType;
                                        db.Sys_ConfigTable.Add(detail);
                                    }
                                    else
                                    {
                                        PromptHelper.Prompt("表编号不能重复！");
                                        return;
                                    }

                                    break;
                                }
                            case DataRowState.Modified:
                                {
                                    string id = tables.Rows[i]["SysTable"].ToString();

                                    try
                                    {
                                        Sys_ConfigTable detail = db.Sys_ConfigTable.First(p => p.SysTable == id);
                                        detail.SysTableName = tables.Rows[i]["SysTableName"].ToString();
                                        var tableType = 0;
                                        if (tables.Rows[i]["TableType"].ToString() == "平台报表配置")
                                        {
                                            tableType = 1;
                                        }
                                        else if (tables.Rows[i]["TableType"].ToString() == "客户数据")
                                        {
                                            tableType = 2;
                                        }
                                        detail.TableType = tableType;
                                    }
                                    catch (Exception ex)
                                    {
                                        PromptHelper.Prompt("未找到要修改的表编号！");
                                        return;
                                    }
                                    break;
                                }
                            case DataRowState.Deleted:
                                {
                                    if (tables.Rows[i]["SysTable", DataRowVersion.Original] != DBNull.Value)
                                    {
                                        try
                                        {
                                            string id = tables.Rows[i]["SysTable", DataRowVersion.Original].ToString();
                                            Sys_ConfigTable detail = db.Sys_ConfigTable.First(p => p.SysTable == id);
                                            db.Sys_ConfigTable.Remove(detail);
                                        }
                                        catch (Exception ex)
                                        {
                                            PromptHelper.Prompt("未找到要删除的表编号！");
                                            return;
                                        }

                                    }
                                    break;
                                }
                        }
                    }
                    db.SaveChanges();
                    GridList_DataBind();
                    PromptHelper.Prompt("保存成功！");
                }
            }
        }

        private void grid_list_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex > -1)
                {
                    var sysTable = this.grid_list.CurrentRow.Cells["ListSysTable"].Value.ToString();
                    if (string.IsNullOrEmpty(sysTable))
                    {
                        this.grid_list.CurrentRow.Cells["ListSysTable"].ReadOnly = false;
                    }
                }
            }
            catch (Exception ex)
            {
                PromptHelper.Prompt(ex.Message);
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            GridList_DataBind();
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            GridList_DataBind();
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            GridList_DataBind();
        }
    }


}
